package com.zp.system.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zp.common.core.constant.CacheNames;
import com.zp.common.core.utils.StreamUtils;
import com.zp.common.core.utils.StringUtils;
import com.zp.common.myBatis.core.page.PageQuery;
import com.zp.common.myBatis.core.page.TableDataInfo;
import com.zp.common.redis.utils.CacheUtils;
import com.zp.system.api.entity.SysBaseDictData;
import com.zp.system.api.entity.SysBaseDictType;
import com.zp.system.entity.bo.SysBaseDictTypeBo;
import com.zp.system.entity.vo.SysBaseDictTypeVo;
import com.zp.system.mapper.SysBaseDictDataMapper;
import com.zp.system.mapper.SysBaseDictTypeMapper;
import com.zp.system.service.ISysBaseDictTypeService;
import lombok.RequiredArgsConstructor;
import org.springframework.cache.annotation.CachePut;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.Comparator;
import java.util.List;
import java.util.Map;

/**
 * 字典类型Service业务层处理
 *
 * @author zhang peng
 * @ date 2023-01-01
 */
@RequiredArgsConstructor
@Service
public class SysBaseDictTypeServiceImpl implements ISysBaseDictTypeService {

    private final SysBaseDictTypeMapper baseMapper;

    private final SysBaseDictDataMapper sysBaseDictDataMapper;

    /**
     * 查询字典类型
     */
    @Override
    public SysBaseDictTypeVo queryById(String baseDictId) {
        return baseMapper.selectVoById(baseDictId);
    }

    /**
     * 查询字典类型列表(分页)
     */
    @Override
    public TableDataInfo<SysBaseDictTypeVo> queryPageList(SysBaseDictTypeBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<SysBaseDictType> lqw = buildQueryWrapper(bo);
        Page<SysBaseDictTypeVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询字典类型列表(不分页)
     */
    @Override
    public List<SysBaseDictTypeVo> queryList(SysBaseDictTypeBo bo) {
        LambdaQueryWrapper<SysBaseDictType> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<SysBaseDictType> buildQueryWrapper(SysBaseDictTypeBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<SysBaseDictType> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(bo.getBaseDictName()), SysBaseDictType::getBaseDictName, bo.getBaseDictName());
        lqw.like(StringUtils.isNotBlank(bo.getDictType()), SysBaseDictType::getDictType, bo.getDictType());
        lqw.eq(StringUtils.isNotBlank(bo.getStatus()), SysBaseDictType::getStatus, bo.getStatus());
        return lqw;
    }

    /**
     * 新增字典类型
     */
    @Override
    @CachePut(cacheNames = CacheNames.SYS_BASE_DICT, key = "#bo.dictType")
    public Boolean insertByBo(SysBaseDictTypeBo bo) {
        SysBaseDictType add = BeanUtil.toBean(bo, SysBaseDictType.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setBaseDictId(add.getBaseDictId());
        }
        return flag;
    }

    /**
     * 修改字典类型
     */
    @Override
    @CachePut(cacheNames = CacheNames.SYS_BASE_DICT, key = "#bo.dictType")
    public Boolean updateByBo(SysBaseDictTypeBo bo) {
        SysBaseDictType oldBaseDict = baseMapper.selectById(bo.getBaseDictId());
        SysBaseDictType update = BeanUtil.toBean(bo, SysBaseDictType.class);
        sysBaseDictDataMapper.update(null, new LambdaUpdateWrapper<SysBaseDictData>()
                .set(SysBaseDictData::getType, bo.getDictType())
                .eq(SysBaseDictData::getType, bo.getDictType()));
        int row = baseMapper.updateById(update);
        if (row > 0) {
            CacheUtils.evict(CacheNames.SYS_BASE_DICT, bo.getDictType());
            return true;
        }
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(SysBaseDictType entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除字典类型
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<String> ids, Boolean isValid) {
        for (String id : ids) {
            //循环删除缓存
            SysBaseDictTypeVo sysBaseDictTypeVo = baseMapper.selectVoById(id);
            CacheUtils.evict(CacheNames.SYS_BASE_DICT, sysBaseDictTypeVo.getDictType());
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    /**
     * 加载字典缓存数据
     */
    @Override
    public void loadingBaseDictCache() {
        List<SysBaseDictData> dictSyaDataList = sysBaseDictDataMapper.selectList(
                new LambdaQueryWrapper<SysBaseDictData>());
        Map<String, List<SysBaseDictData>> dictDataMap = StreamUtils.groupByKey(dictSyaDataList, SysBaseDictData::getType);
        dictDataMap.forEach((k, v) -> {
            List<SysBaseDictData> dictList = StreamUtils.sorted(v, Comparator.comparing(SysBaseDictData::getSort));
            CacheUtils.put(CacheNames.SYS_BASE_DICT, k, dictList);
        });
    }

    /**
     * 清空字典缓存数据
     */
    public void clearDictCache() {
        CacheUtils.clear(CacheNames.SYS_BASE_DICT);
    }

    /**
     * 重置字典缓存数据
     */
    @Override
    public void resetDictCache() {
        clearDictCache();
        loadingBaseDictCache();
    }
}
